from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes

# 密钥必须为16、24或32字节长（对应AES-128、AES-192或AES-256）
key = get_random_bytes(32)  # 生成随机密钥
iv = get_random_bytes(16)  # 初始化向量 (IV)，对于CBC模式来说也是必需的
msg = b"hello world; this is a secret message"


# 加密
def AES_encrypt(msg, key, iv):
    aes_impl = AES.new(key, AES.MODE_CBC, iv)
    encrypt_msg = aes_impl.encrypt(pad(msg, AES.block_size))
    return encrypt_msg


# 解密
def AES_decrypt(encrypted_hex, key, iv):
    aes_impl = AES.new(key, AES.MODE_CBC, iv)
    decrypt_msg = unpad(aes_impl.decrypt(encrypted_hex), AES.block_size)
    return decrypt_msg


encrypt_msg = AES_encrypt(msg, key, iv)
decrypt_msg = AES_decrypt(encrypt_msg, key, iv)
print("加密数据", encrypt_msg)
print("解密数据", decrypt_msg)

""" 结果:
加密数据 b'\x18`c\xc5\x8c#\nt\x19\xf2x\xfa\xf2U\xb0\xa4\x07\xb4\x87\x89\xab\xa2\xbciNMxO\xa7(\x15\x11\xb3\xae\xdb\xca\xbb\x04*Y>\xba\xda\xdc\x85(\x15^'
解密数据 b'hello world; this is a secret message'
"""